package com.java.simple.study.jvm.classloader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author zhoujunlin
 * @date 2023年01月31日 11:23
 * @desc 类的主动使用
 * -XX:+TraceClassLoading   打印类的加载信息
 */
public class ActiveUse {

    public static void main(String[] args) throws ClassNotFoundException {
        //testSerializable();
        //testStaticField();
        testReflect();
    }

    public static void testReflect() throws ClassNotFoundException {
        // 反射获取类的实例  主动使用   会导致类的init
        Class.forName("com.java.simple.study.jvm.classloader.User");
    }

    public static void testStaticField() {
        System.out.println(User.num);
        System.out.println("--------------");
        System.out.println(User.num2);
        System.out.println("----------------");
    }

    public static void testSerializable() {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            // 序列化
            /*oos = new ObjectOutputStream(new FileOutputStream("order.dat"));
            oos.writeObject(new Order());*/
            System.out.println("====================");
            // 反序列化
            ois = new ObjectInputStream(new FileInputStream("order.dat"));
            Order order = (Order) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}


class Order implements Serializable {
    static {
        // 只会被调用一次
        System.out.println("Order类的初始化");
    }
}

class User {

    static {
        System.out.println("User类的初始化");
    }

    public static final int num = 1;
    public static int num2 = 2;

}
